
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="GRPC初识">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>GRPC初识 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        GRPC初识
      </h1>
      <span>
        
        <time class="time" datetime="2020-02-11T16:00:00.000Z">
        2020-02-12
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>RPC算是近些年比较火热的概念了，随着微服务架构的兴起，RPC的应用越来越广泛。本文介绍了RPC和gRPC的相关概念，并且通过详细的代码示例介绍了gRPC的基本使用。</p>
<h1 id="gRPC"><a href="#gRPC" class="headerlink" title="gRPC"></a>gRPC</h1><h2 id="RPC是什么"><a href="#RPC是什么" class="headerlink" title="RPC是什么"></a>RPC是什么</h2><p>在分布式计算，远程过程调用（英语：Remote Procedure Call，缩写为 RPC）是一个计算机通信协议。该协议允许运行于一台计算机的程序调用另一个地址空间（通常为一个开放网络的一台计算机）的子程序，而程序员就像调用本地程序一样，无需额外地为这个交互作用编程（无需关注细节）。RPC是一种服务器-客户端（Client/Server）模式，经典实现是一个通过<code>发送请求-接受回应</code>进行信息交互的系统。</p>
<h2 id="gRPC是什么"><a href="#gRPC是什么" class="headerlink" title="gRPC是什么"></a>gRPC是什么</h2><p><code>gRPC</code>是一种现代化开源的高性能RPC框架，能够运行于任意环境之中。最初由谷歌进行开发。它使用HTTP/2作为传输协议。</p>
<p>在gRPC里，客户端可以像调用本地方法一样直接调用其他机器上的服务端应用程序的方法，帮助你更容易创建分布式应用程序和服务。与许多RPC系统一样，gRPC是基于定义一个服务，指定一个可以远程调用的带有参数和返回类型的的方法。在服务端程序中实现这个接口并且运行gRPC服务处理客户端调用。在客户端，有一个stub提供和服务端相同的方法。<img src="https://www.liwenzhou.com/images/Go/grpc/grpc.svg" alt="grpc"></p>
<h2 id="为什么要用gRPC"><a href="#为什么要用gRPC" class="headerlink" title="为什么要用gRPC"></a>为什么要用gRPC</h2><p>使用gRPC， 我们可以一次性的在一个<code>.proto</code>文件中定义服务并使用任何支持它的语言去实现客户端和服务端，反过来，它们可以应用在各种场景中，从Google的服务器到你自己的平板电脑—— gRPC帮你解决了不同语言及环境间通信的复杂性。使用<code>protocol buffers</code>还能获得其他好处，包括高效的序列号，简单的IDL以及容易进行接口更新。总之一句话，使用gRPC能让我们更容易编写跨语言的分布式代码。</p>
<h2 id="安装gRPC"><a href="#安装gRPC" class="headerlink" title="安装gRPC"></a>安装gRPC</h2><h3 id="安装gRPC-1"><a href="#安装gRPC-1" class="headerlink" title="安装gRPC"></a>安装gRPC</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">go get -u google.golang.org/grpc</span><br></pre></td></tr></table></figure>

<h3 id="安装Protocol-Buffers-v3"><a href="#安装Protocol-Buffers-v3" class="headerlink" title="安装Protocol Buffers v3"></a>安装Protocol Buffers v3</h3><p>安装用于生成gRPC服务代码的协议编译器，最简单的方法是从下面的链接：<a href="https://github.com/google/protobuf/releases下载适合你平台的预编译好的二进制文件（`protoc--.zip`）。" target="_blank" rel="noopener">https://github.com/google/protobuf/releases下载适合你平台的预编译好的二进制文件（`protoc--.zip`）。</a></p>
<p>下载完之后，执行下面的步骤：</p>
<ol>
<li>解压下载好的文件</li>
<li>把<code>protoc</code>二进制文件的路径加到环境变量中</li>
</ol>
<p>接下来执行下面的命令安装protoc的Go插件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">go get -u github.com/golang/protobuf/protoc-gen-go</span><br></pre></td></tr></table></figure>

<p>编译插件<code>protoc-gen-go</code>将会安装到<code>$GOBIN</code>，默认是<code>$GOPATH/bin</code>，它必须在你的<code>$PATH</code>中以便协议编译器<code>protoc</code>能够找到它。</p>
<h3 id="安装指定"><a href="#安装指定" class="headerlink" title="安装指定"></a>安装指定</h3><h2 id="gRPC开发分三步"><a href="#gRPC开发分三步" class="headerlink" title="gRPC开发分三步"></a>gRPC开发分三步</h2><p>把大象放进冰箱分几步？</p>
<ol>
<li>把冰箱门打开。</li>
<li>把大象放进去。</li>
<li>把冰箱门带上。</li>
</ol>
<p>gRPC开发同样分三步：</p>
<ol>
<li>编写<code>.proto</code>文件，生成指定语言源代码。</li>
<li>编写服务端代码</li>
<li>编写客户端代码</li>
</ol>
<h2 id="gRPC入门示例"><a href="#gRPC入门示例" class="headerlink" title="gRPC入门示例"></a>gRPC入门示例</h2><h3 id="编写proto代码"><a href="#编写proto代码" class="headerlink" title="编写proto代码"></a>编写proto代码</h3><p>gRPC是基于Protocol Buffers。</p>
<p><code>Protocol Buffers</code>是一种与语言无关，平台无关的可扩展机制，用于序列化结构化数据。使用<code>Protocol Buffers</code>可以一次定义结构化的数据，然后可以使用特殊生成的源代码轻松地在各种数据流中使用各种语言编写和读取结构化数据。</p>
<p>关于<code>Protocol Buffers</code>的教程可以自行在网上搜索，本文默认读者熟悉<code>Protocol Buffers</code>。</p>
<figure class="highlight protobuf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">syntax = &quot;proto3&quot;; // 版本声明，使用Protocol Buffers v3版本</span><br><span class="line"></span><br><span class="line">package pb; // 包名</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">// 定义一个打招呼服务</span><br><span class="line">service Greeter &#123;</span><br><span class="line">    // SayHello 方法</span><br><span class="line">    rpc SayHello (HelloRequest) returns (HelloReply) &#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 包含人名的一个请求消息</span><br><span class="line">message HelloRequest &#123;</span><br><span class="line">    string name = 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 包含问候语的响应消息</span><br><span class="line">message HelloReply &#123;</span><br><span class="line">    string message = 1;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行下面的命令，生成go语言源代码：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">protoc -I helloworld/ helloworld/pb/helloworld.proto --go_out=plugins=grpc:helloworld</span><br></pre></td></tr></table></figure>

<p>在<code>gRPC_demo/helloworld/pb</code>目录下会生成<code>helloworld.pb.go</code>文件。</p>
<h3 id="编写Server端Go代码"><a href="#编写Server端Go代码" class="headerlink" title="编写Server端Go代码"></a>编写Server端Go代码</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line">	<span class="string">"net"</span></span><br><span class="line"></span><br><span class="line">	pb <span class="string">"gRPC_demo/helloworld/pb"</span></span><br><span class="line">	<span class="string">"golang.org/x/net/context"</span></span><br><span class="line">	<span class="string">"google.golang.org/grpc"</span></span><br><span class="line">	<span class="string">"google.golang.org/grpc/reflection"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> server <span class="keyword">struct</span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(s *server)</span> <span class="title">SayHello</span><span class="params">(ctx context.Context, in *pb.HelloRequest)</span> <span class="params">(*pb.HelloReply, error)</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> &amp;pb.HelloReply&#123;Message: <span class="string">"Hello "</span> + in.Name&#125;, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 监听本地的8972端口</span></span><br><span class="line">	lis, err := net.Listen(<span class="string">"tcp"</span>, <span class="string">":8972"</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"failed to listen: %v"</span>, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	s := grpc.NewServer() <span class="comment">// 创建gRPC服务器</span></span><br><span class="line">	pb.RegisterGreeterServer(s, &amp;server&#123;&#125;) <span class="comment">// 在gRPC服务端注册服务</span></span><br><span class="line"></span><br><span class="line">	reflection.Register(s) <span class="comment">//在给定的gRPC服务器上注册服务器反射服务</span></span><br><span class="line">	<span class="comment">// Serve方法在lis上接受传入连接，为每个连接创建一个ServerTransport和server的goroutine。</span></span><br><span class="line">	<span class="comment">// 该goroutine读取gRPC请求，然后调用已注册的处理程序来响应它们。</span></span><br><span class="line">	err = s.Serve(lis)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"failed to serve: %v"</span>, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将上面的代码保存到<code>gRPC_demo/helloworld/server/server.go</code>文件中，编译并执行：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> helloworld/server</span><br><span class="line">go build</span><br><span class="line">./server</span><br></pre></td></tr></table></figure>

<h3 id="编写Client端Go代码"><a href="#编写Client端Go代码" class="headerlink" title="编写Client端Go代码"></a>编写Client端Go代码</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">"context"</span></span><br><span class="line">	<span class="string">"fmt"</span></span><br><span class="line"></span><br><span class="line">	pb <span class="string">"gRPC_demo/helloworld/pb"</span></span><br><span class="line">	<span class="string">"google.golang.org/grpc"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 连接服务器</span></span><br><span class="line">	conn, err := grpc.Dial(<span class="string">":8972"</span>, grpc.WithInsecure())</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"faild to connect: %v"</span>, err)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> conn.Close()</span><br><span class="line"></span><br><span class="line">	c := pb.NewGreeterClient(conn)</span><br><span class="line">	<span class="comment">// 调用服务端的SayHello</span></span><br><span class="line">	r, err := c.SayHello(context.Background(), &amp;pb.HelloRequest&#123;Name: <span class="string">"szk"</span>&#125;)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(<span class="string">"could not greet: %v"</span>, err)</span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Printf(<span class="string">"Greeting: %s !\n"</span>, r.Message)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将上面的代码保存到<code>gRPC_demo/helloworld/client/client.go</code>文件中，编译并执行：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> helloworld/client/</span><br><span class="line">go build</span><br><span class="line">./client</span><br></pre></td></tr></table></figure>

<p>得到输出如下（注意要先启动server端再启动client端）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ ./client </span><br><span class="line">Greeting: Hello szk!</span><br></pre></td></tr></table></figure>

<p>此时我们的目录结构如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">./gRPC_demo</span><br><span class="line">├── go.mod</span><br><span class="line">├── go.sum</span><br><span class="line">└── helloworld</span><br><span class="line">    ├── client</span><br><span class="line">    │   ├── client</span><br><span class="line">    │   └── client.go</span><br><span class="line">    │   ├── client.py</span><br><span class="line">    ├── pb</span><br><span class="line">    │   ├── helloworld.pb.go</span><br><span class="line">    │   └── helloworld.proto</span><br><span class="line">    └── server</span><br><span class="line">        ├── server</span><br><span class="line">        └── server.go</span><br></pre></td></tr></table></figure>

<h3 id="gRPC跨语言调用"><a href="#gRPC跨语言调用" class="headerlink" title="gRPC跨语言调用"></a>gRPC跨语言调用</h3><p>接下来，我们演示一下如何使用gRPC实现跨语言的RPC调用。</p>
<p>我们使用<code>Python</code>语言编写<code>Client</code>，然后向上面使用<code>go</code>语言编写的<code>server</code>发送RPC请求。</p>
<h3 id="生成Python代码"><a href="#生成Python代码" class="headerlink" title="生成Python代码"></a>生成Python代码</h3><p>在<code>gRPC_demo</code>目录执行下面的命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python -m grpc_tools.protoc -I helloworld/pb/ --python_out=helloworld/client/ --grpc_python_out=helloworld/client/ helloworld/pb/helloworld.proto</span><br></pre></td></tr></table></figure>

<p>上面的命令会在<code>gRPC_demo/helloworld/client/</code>目录生成如下两个python文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">helloworld_pb2.py</span><br><span class="line">helloworld_pb2_grpc.py</span><br></pre></td></tr></table></figure>

<h3 id="编写Python版Client"><a href="#编写Python版Client" class="headerlink" title="编写Python版Client"></a>编写Python版Client</h3><p>在``gRPC_demo/helloworld/client/<code>目录闯将</code>client.py`文件，其内容如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> grpc</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> helloworld_pb2</span><br><span class="line"><span class="keyword">import</span> helloworld_pb2_grpc</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="comment"># 注意(gRPC Python Team): .close()方法在channel上是可用的。</span></span><br><span class="line">    <span class="comment"># 并且应该在with语句不符合代码需求的情况下使用。</span></span><br><span class="line">    <span class="keyword">with</span> grpc.insecure_channel(<span class="string">'localhost:8972'</span>) <span class="keyword">as</span> channel:</span><br><span class="line">        stub = helloworld_pb2_grpc.GreeterStub(channel)</span><br><span class="line">        response = stub.SayHello(helloworld_pb2.HelloRequest(name=<span class="string">'szk'</span>))</span><br><span class="line">    print(<span class="string">"Greeter client received: &#123;&#125;!"</span>.format(response.message))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    logging.basicConfig()</span><br><span class="line">    run()</span><br></pre></td></tr></table></figure>

<p>将上面的代码保存执行，得到输出结果如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gRPC_demo $ python helloworld/client/client.py </span><br><span class="line">Greeter client received: Hello q1mi!</span><br></pre></td></tr></table></figure>

<p>这里我们就实现了，使用python代码编写的client去调用Go语言版本的server了。</p>
<p>点击右边的链接查看完整代码：<a href="https://github.com/Q1mi/gRPC_demo" target="_blank" rel="noopener">gRPC_demo完整代码</a></p>
<p>gRPC还有更多进阶用法，未完待续…</p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#gRPC"><span class="toc-text">gRPC</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#RPC是什么"><span class="toc-text">RPC是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#gRPC是什么"><span class="toc-text">gRPC是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#为什么要用gRPC"><span class="toc-text">为什么要用gRPC</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#安装gRPC"><span class="toc-text">安装gRPC</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#安装gRPC-1"><span class="toc-text">安装gRPC</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#安装Protocol-Buffers-v3"><span class="toc-text">安装Protocol Buffers v3</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#安装指定"><span class="toc-text">安装指定</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#gRPC开发分三步"><span class="toc-text">gRPC开发分三步</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#gRPC入门示例"><span class="toc-text">gRPC入门示例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#编写proto代码"><span class="toc-text">编写proto代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#编写Server端Go代码"><span class="toc-text">编写Server端Go代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#编写Client端Go代码"><span class="toc-text">编写Client端Go代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gRPC跨语言调用"><span class="toc-text">gRPC跨语言调用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#生成Python代码"><span class="toc-text">生成Python代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#编写Python版Client"><span class="toc-text">编写Python版Client</span></a></li></ol></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/02/03/几个简单的linux调试工具/" rel="next" title="linux调优的几个工具">
          linux调优的几个工具
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/04/26/第一章Python的介绍和安装/" rel="prev" title="第一章 Python的简介和安装">
            第一章 Python的简介和安装
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
